﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace WadViewer.DomainModel
{
	/// <summary>
	/// Accessor class for access to Windows Azure Table Storage
	/// </summary>
	internal class StorageAccessor
	{
		// the credentials
		private StorageCredentials credentials;

		// the data context
		private TableServiceContext context;

		/// <summary>
		/// constructor
		/// </summary>
		/// <param name="baseAddress">url to table storage</param>
		/// <param name="accountName">account name</param>
		/// <param name="key">secret key</param>
		public StorageAccessor(string baseAddress, string accountName, string key)
		{
			this.credentials = new StorageCredentialsAccountAndKey(accountName, key);
			this.context = new TableServiceContext(baseAddress, credentials);
		}

		/// <summary>
		/// Retrieves a collection of entities
		/// </summary>
		/// <typeparam name="TEntity">type of entity to retrieve</typeparam>
		/// <param name="tableName">name of the table</param>
		/// <param name="from">from date and time (inclusive)</param>
		/// <param name="to">end date and time (exclusive)</param>
		/// <param name="maxResult">maximum number of items to return</param>
		/// <returns>collection of entities</returns>
		public IEnumerable<TEntity> Retrieve<TEntity>(string tableName, DateTime from, DateTime to, int maxResult) where TEntity : TableServiceEntity
		{
			return context.CreateQuery<TEntity>(tableName)
					.Where(w => w.Timestamp >= from)
					.Where(w => w.Timestamp < to)
					.Take(maxResult)
					.AsTableServiceQuery()
					.Execute();
		}
	}
}
